/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package safemedicalsolution.net;

import java.io.IOException;

import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;



/**
 *
 * @author Saad
 */
public class RabbitClient implements Runnable {
    
    private static final Logger log = LoggerFactory.getLogger("RabbitClient");
            
    private String host;
    private int port;
    private Connection conn;
    private Channel ch;
    
    public RabbitClient(String hostname, int portNumber){
        
        this.host = hostname;
        this.port = portNumber;
    }
    
    public RabbitClient(String hostname) {
        
        this.host = hostname;
        this.port = AMQP.PROTOCOL.PORT;
    }
            
    
    public int initConnection(String routingKey){
       
        int hresult = -1;
        
        try {
            
            ConnectionFactory cfConn = new ConnectionFactory();
            cfConn.setUsername("guest");
            cfConn.setPassword("guest");
            cfConn.setVirtualHost("/");
            cfConn.setHost(host);
            cfConn.setPort(port);
            conn = cfConn.newConnection();
            
            ch = conn.createChannel();
            ch.queueDeclare(routingKey, false, false, false, null);
            
            hresult = 1;
        }
        catch (IOException ex) {
            log.error(ex.getMessage(), ex);  
        }
        
        return 1;

    }
    
    public int sendMessage(String exchange, String routingKey, String message){
        
        try{
             ch.basicPublish(exchange, routingKey, null, message.getBytes());
             log.info("{}|{}","OUT",message);
        }
        catch(Exception ex){
            log.error(ex.getMessage(), ex);
        }
        
        
        return 1;
    }
    
    public int closeConnection() {
            
        try{
            
            if ( ch != null) ch.close();
            if ( conn != null ) conn.close();
        } 
        catch (IOException ex) {
           log.error(ex.getMessage(), ex);
        }
        
        return  1;
    }
    
    private String queueName;
    private Thread thread;
    private boolean isRunning = false;
    
    public void startListening(String queueName){
        this.queueName = queueName;
        this.isRunning = true;
        thread = new Thread(this);
        thread.setName("msg-lstnr");
        thread.setDaemon(true);
        thread.start();
    }
    public void stopListening(){ 
        isRunning = false;
    }

    @Override
    public void run() {
        try{
            QueueingConsumer consumer = new QueueingConsumer(ch);
            ch.basicConsume(queueName, consumer);
            
            while (isRunning) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery(200);
                
                if ( delivery != null && delivery.getBody().length > 0 ) {
                    log.info("{}|{}","IN",new String(delivery.getBody()));
                    ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                }
            }
            
            log.debug("Gracefully exiting thread");
        }
        catch(Exception ex){
            log.error(ex.getMessage(), ex);
        }
    }
    
     public static void main(String[] args) {
        
        RabbitClient rc = new RabbitClient("localhost");
        rc.initConnection("FileLine");
        rc.startListening("FileLine");
        for( int i=0; i < 10; i++ ){
            rc.sendMessage("", "FileLine", "Hello World" + i );
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                
            }
        }
        rc.stopListening();
        
        
        rc.closeConnection();   
        //RabbitClient rc1 = new RabbitClient("localhost");
        //rc1.initConnection("FileLine");
        //rc1.sendMessage("", "FileLine", "Hello World");
     }
}
